<?php


/**
* CakePHP Schema Plugin
* http://cake-schema-plugin.googlecode.com
*
* @package schema
* @subpackage schema.config.schema
* @author Ivan Chistyakov <zetruger@gmail.com>
* @version $Id: habtm_auto.php 118 2010-10-17 04:59:20Z zetruger@gmail.com $
* @link $HeadURL: http://cake-schema-plugin.googlecode.com/svn/trunk/config/schema/habtm_auto.php $
* @license MIT License (http://opensource.org/licenses/mit-license.php)
*/


class HabtmAutoSchema extends CakeSchema {

var $name = 'HabtmAuto';

function __construct($options = array()) {
	parent::__construct($options);
	foreach (App::objects('model') as $modelClass) {
		if (App::import('Model', $modelClass)) {
			$modelVars = get_class_vars($modelClass);
			if (isset($modelVars['hasAndBelongsToMany'])) {
				$table1 = Inflector::tableize($modelClass);
				foreach ($modelVars['hasAndBelongsToMany'] as $assocAlias => $assocSpecifics) {
					if (is_string($assocSpecifics)) {
						$table2 = Inflector::tableize($assocSpecifics);
					} elseif (is_array($assocSpecifics)) {
						if (isset($assocSpecifics['joinTable'])) {
							//$table2 = $assocSpecifics['joinTable'];
						} elseif (isset($assocSpecifics['className'])) {
							$table2 = Inflector::tableize($assocSpecifics['className']);
						} else {
							$table2 = Inflector::tableize($assocAlias);
						}
					} else {
						continue;
					}
					$foreignKey1 = Inflector::singularize($table1) . '_id';
					$foreignKey2 = Inflector::singularize($table2) . '_id';
					if (is_array($assocSpecifics)) {
						if (isset($assocSpecifics['foreignKey'])) {
							$foreignKey1 = $assocSpecifics['foreignKey'];
						}
						if (isset($assocSpecifics['associationForeignKey'])) {
							$foreignKey2 = $assocSpecifics['associationForeignKey'];
						}
					}
					if ($table1 <= $table2) {
						$table = $table1 . '_' . $table2;
						$foreignKey = $foreignKey1;
						$associationForeignKey = $foreignKey2;
					} else {
						$table = $table2 . '_' . $table1;
						$foreignKey = $foreignKey2;
						$associationForeignKey = $foreignKey1;
					}
					$this->tables[$table] = array(
						'id' => array('type'=>'integer', 'null' => FALSE, 'default' => NULL, 'key' => 'primary'),
						$foreignKey => array('type'=>'integer', 'null' => FALSE, 'key' => 'index'),
						$associationForeignKey => array('type'=>'integer', 'null' => FALSE, 'key' => 'index'),
						'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'habtm' => array('column' => array($foreignKey, $associationForeignKey), 'unique' => 1))
					);
				}
			}
		}
	}
}

}


?>